package com.gqp.engine;

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * 解压7z
 */
public class UnSevenZ implements UnCompress{
    public static void main(String[] args) {
        try {
            // unSevenZ("C:\\Users\\86166\\Desktop\\rr\\测试.7z", "C:\\Users\\86166\\Desktop\\7z\\测试");
            System.out.println("7z解压完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String inputFile;
    private String destDirPath;

    public UnSevenZ(String inputFile, String destDirPath) {
        this.inputFile = inputFile;
        this.destDirPath = destDirPath;
    }
    @Override
    public void unCompress() {
        try {
            unSevenZ(inputFile, destDirPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void unSevenZ(String inputFile, String destDirPath) throws Exception {
        /**
         * zip解压
         * @param inputFile 待解压文件名
         * @param destDirPath  解压路径
         */
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        SevenZFile zIn = new SevenZFile(srcFile);
        SevenZArchiveEntry entry = null;
        File file = null;
        while ((entry = zIn.getNextEntry()) != null) {
            OutputStream out = null;
            BufferedOutputStream bos = null;
            try {
                if (!entry.isDirectory()) {
                    file = new File(destDirPath, entry.getName());
                    if (!file.exists()) {
                        new File(file.getParent()).mkdirs();//创建此文件的上级目录
                    }
                    out = new FileOutputStream(file);
                    bos = new BufferedOutputStream(out);
                    int len = -1;
                    byte[] buf = new byte[1024];
                    while ((len = zIn.read(buf)) != -1) {
                        bos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
//                    bos.close();
//                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bos!=null){
                    bos.close();
                }
                if (out!=null){
                    out.close();
                }
            }
        }
    }


}
